import { api } from './api'
import type { ApiResponse, PaginatedResponse, PaginationParams } from '../types'
import { Category } from '../../types/article'

interface CreateCategoryRequest {
  name: string
  description?: string
}

interface UpdateCategoryRequest {
  name?: string
  description?: string
}

export const categoriesApi = api.injectEndpoints({
  endpoints: (builder) => ({
    getCategories: builder.query<ApiResponse<Category[]>, void>({
      query: () => '/categories',
      providesTags: (result) =>
        result
          ? [
              ...result.data.map(({ id }) => ({ type: 'Category' as const, id })),
              { type: 'Category' as const, id: 'LIST' }
            ]
          : [{ type: 'Category' as const, id: 'LIST' }]
    }),

    getAllCategories: builder.query<ApiResponse<Category[]>, void>({
      query: () => '/categories/all',
      providesTags: [{ type: 'Category', id: 'LIST' }],
    }),

    getCategory: builder.query<ApiResponse<Category>, number>({
      query: (id) => `/categories/${id}`,
      providesTags: (_, __, id) => [{ type: 'Category' as const, id }]
    }),

    createCategory: builder.mutation<
      ApiResponse<Category>,
      Pick<Category, 'name' | 'description'>
    >({
      query: (data) => ({
        url: '/categories',
        method: 'POST',
        body: data
      }),
      invalidatesTags: [{ type: 'Category', id: 'LIST' }]
    }),

    updateCategory: builder.mutation<
      ApiResponse<Category>,
      Partial<Category> & Pick<Category, 'id'>
    >({
      query: ({ id, ...data }) => ({
        url: `/categories/${id}`,
        method: 'PUT',
        body: data
      }),
      invalidatesTags: (_, __, { id }) => [
        { type: 'Category', id },
        { type: 'Category', id: 'LIST' }
      ]
    }),

    deleteCategory: builder.mutation<void, number>({
      query: (id) => ({
        url: `/categories/${id}`,
        method: 'DELETE'
      }),
      invalidatesTags: (_, __, id) => [
        { type: 'Category', id },
        { type: 'Category', id: 'LIST' }
      ]
    })
  })
})

export const {
  useGetCategoriesQuery,
  useGetAllCategoriesQuery,
  useGetCategoryQuery,
  useCreateCategoryMutation,
  useUpdateCategoryMutation,
  useDeleteCategoryMutation
} = categoriesApi 